package util;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.web.multipart.MultipartFile;

public class UploadImg {

	public static String uploadImg(String path, MultipartFile uploadpic, int userId) throws Exception {

		String userPhoto = "";

		String fileName = uploadpic.getOriginalFilename();

		String ext = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
		ext = ext.toLowerCase();

		String pic_name = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + userId;
		userPhoto = pic_name + "." + ext;
		String filePath = path + "\\" + userPhoto;

		InputStream stream = uploadpic.getInputStream();
		FileOutputStream fs = new FileOutputStream(filePath);
		byte[] buffer = new byte[1024 * 1024];
		int byteread = 0;
		while ((byteread = stream.read(buffer)) != -1) {
			fs.write(buffer, 0, byteread);
			fs.flush();
		}
		fs.close();
		stream.close();
		return userPhoto;
	}
}
